package com.example.pathprotectsystem.controller;
import com.example.pathprotectsystem.pojo.Password;
import com.example.pathprotectsystem.pojo.Result;
import com.example.pathprotectsystem.pojo.User;
import com.example.pathprotectsystem.service.BindService;
import com.example.pathprotectsystem.service.UserService;
import com.example.pathprotectsystem.utils.JwtUtil;
import com.example.pathprotectsystem.utils.Md5Util;
import com.example.pathprotectsystem.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BindService bindService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //前端校验参数
    @PostMapping("/register")
    public Result register(String userName, String passWord, String rePassWord){
        System.out.println(userName);
        System.out.println(passWord);
        System.out.println(rePassWord);
        User user = userService.findByUserName(userName);
        if(user!=null) return Result.error("该用户名已被注册！");
        if(userName.isEmpty()||passWord.isEmpty()||passWord.isEmpty())return Result.error("信息填写不完整");
        if(userName.length()<5||userName.length()>=17) return Result.error("用户名的长度必须为5~16位");
        if(passWord.length()<5||passWord.length()>=17) return  Result.error("密码长度必须为5~16位");
        if(!passWord.equals(rePassWord)) return Result.error("请确保两次输入的密码一样");
        userService.register(userName,passWord);
        return Result.success();
    }
    @PostMapping("/login")
    public Result login(String userName,String passWord){
        //根据用户名查询用户
        User loginuser = userService.findByUserName(userName);
        //判断该用户是否存在
        if(loginuser==null)return Result.error("用户名错误！");
        System.out.println(Md5Util.getMD5String(passWord));
        //判断密码是否正确  loginuser对象中的password是密文
        if(Md5Util.getMD5String(passWord).equals(loginuser.getPassWord())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginuser.getId());
            claims.put("username",loginuser.getUserName());
            String token = JwtUtil.genToken(claims); //
            //将token存储到Redis中
            System.out.println("token"+token);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        //根据用户名查询用户
        Map<String,Object> map = ThreadLocalUtil.get();
        System.out.println("个人信息");
        System.out.println(map);
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }
    @GetMapping("/getpart")
    public Result<List<User>>listpart(String str){
        List<User> p = userService.listpart(str);
        return Result.success(p);
    }
    @DeleteMapping("/delete")
    public Result delete(Integer id){
        int sum = bindService.findUserIdFromTask(id);
        if(sum==0){
            userService.delete(id);
            return Result.success();
        }
        return Result.error("有巡查或检查任务存在该人员信息，无法删除！");
    }
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        if(user.getNickName().isEmpty()||user.getEmail().isEmpty()){
            return Result.error("信息填写不完整");
        }
        if(user.getNickName().length()<2||user.getNickName().length()>=11)
            return Result.error("昵称的长度必须为2~10位");
        if(!pattern.matcher(user.getEmail()).matches()){
            return Result.error("邮箱格式不正确");
        }
        System.out.println(user);
        userService.update(user);
        return  Result.success();
    }
    @PutMapping("/updateall")
    public Result updateall(@RequestBody User user){
        System.out.println(user);
        Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        if(user.getNickName().isEmpty()||user.getEmail().isEmpty()||
                user.getUserName().isEmpty()){
            return Result.error("信息填写不完整");
        }
        if(user.getRadio().equals("1")){
            userService.initPassWord(user.getId());
        }
        if(user.getUserName().length()<5||user.getUserName().length()>=17)
            return Result.error("用户名的长度必须为5~16位");
        if(user.getNickName().length()<2||user.getNickName().length()>=11)
            return Result.error("昵称的长度必须为2~10位");
        if(!pattern.matcher(user.getEmail()).matches()){
            return Result.error("邮箱格式不正确");
        }
        System.out.println(user);
        userService.update(user);
        return  Result.success();
    }
    @PutMapping("/updateavatar")
    public Result updateavatar(@RequestBody User user){
        System.out.println(user);
        userService.updateavatar(user);
        return  Result.success();
    }
    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Password password, @RequestHeader("Authorization") String token){
        //1.校验参数
        String oldPwd = password.getOldPassword();
        String newPwd =  password.getNewPassword();
        String rePwd =  password.getRePassword();
        if(!StringUtils.hasLength(oldPwd)|| !StringUtils.hasLength(newPwd)|| !StringUtils.hasLength(rePwd)){
            return Result.error("信息填写不完整");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，在和old_pwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginuser = userService.findByUserName(username);
        if(!loginuser.getPassWord().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }
        //newPwd和rePwd是否一样
        if (!newPwd.equals(rePwd)) return Result.error("确认密码和新密码不同");
        userService.updatePwd(password);
        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
